const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const mime = require('mime');

app.use(express.static('.'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get('/', function (req, res) {
    res.send('Hello World');
});

app.get('/prepare', async function (req, res) {
    try {
        let file = __dirname + '/zhuoku220.jpg';
        let pagesize = 1024 * 100;//100kb
        let filehandle = await fs.promises.open(file);
        let stat = await filehandle.stat();
        let total_page = Math.ceil(stat.size / pagesize);
        res.json({
            code: 1,
            msg: 'success',
            data: {
                total_page: total_page,
                mime: mime.getType(file),
                filename: path.basename(file),
            },
        });
        await filehandle.close();
    } catch (err) {
        console.error(err);
        res.json({
            code: 0,
            msg: err.toString(),
            data: {
                total_page: 0,
                mime: '',
                filename: '',
            },
        });
    }
});

app.get('/download', async function (req, res) {
    let page = parseInt(req.query.page) || 1;
    try {
        let file = __dirname + '/zhuoku220.jpg';
        let pagesize = 1024 * 100;//100kb
        let position = (page - 1) * pagesize;
        let filehandle = await fs.promises.open(file);
        let stat = await filehandle.stat();
        let total_page = Math.ceil(stat.size / pagesize);
        if (page > total_page) {
            res.send('Wrong page number');
            return;
        }
        let bufferLength = Math.min(pagesize, stat.size - (page - 1) * pagesize);
        let readBuffer = new Buffer(bufferLength);
        let result = await filehandle.read(readBuffer, 0, bufferLength, position);
        //console.log(result.buffer.toString('hex'));

        await filehandle.close();
        res.send(Buffer.from(result.buffer));

    } catch (err) {
        console.error(err);
        res.sendStatus(500);
        res.send(err.toString());
    }

    return;
});

app.get('/wrong', async function (req, res) {
    res.json({
        code: 0,
        msg: 'fail',
        data: {

        },
    });
});

app.listen(4000);